package com.taptech.doufu.app;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.taptech.doufu.ui.activity.MainHomeActivity;
import com.taptech.doufu.util.DiaoBaoPath;
import com.taptech.doufu.util.ExceptionInfo;
import com.taptech.doufu.util.TimeDateFunction;
import com.taptech.doufu.util.XmlOperate;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;


public class UEHandler implements Thread.UncaughtExceptionHandler {
	public static UEHandler instances = new UEHandler();
	private Context mContext;
	// 系统默认的UncaughtException处理类
	private Thread.UncaughtExceptionHandler mDefaultHandler;
	private UEHandler() {

	}

	public static UEHandler getInstances() {
		return instances;
	}


	/**
	 * 初始化
	 *
	 * @param context
	 */
	public void init(Context context) {
		mContext = context;
		// 获取系统默认的UncaughtException处理器
		mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
		// 设置该CrashHandler为程序的默认处理器
		Thread.setDefaultUncaughtExceptionHandler(this);
	}

	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		String info = null;
		ByteArrayOutputStream baos = null;
		PrintStream printStream = null;
		try {
			baos = new ByteArrayOutputStream();
			printStream = new PrintStream(baos);
			ex.printStackTrace(printStream);
			byte[] data = baos.toByteArray();
			info = new String(data);
			data = null;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (printStream != null) {
					printStream.close();
				}
				if (baos != null) {
					baos.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		// print
		long threadId = thread.getId();
		Log.d("ANDROID_LAB", "Thread.getName()=" + thread.getName() + " id=" + threadId + " state=" + thread.getState());
		Log.d("ANDROID_LAB", "Error[" + info + "]");
		String path= DiaoBaoPath.getErrorLogPath();
		//创建xml文件
		if(!new File(path).exists())
		{
			XmlOperate.createXMLFile(path);
		}
		//获取当前时间
		long timeInMillis= TimeDateFunction.getCurrTime();
		ExceptionInfo exceptInfo=new ExceptionInfo(info,TimeDateFunction.toDateTime(timeInMillis),timeInMillis);
	    //添加文件节点
		XmlOperate.addNode(path, exceptInfo);
		mDefaultHandler.uncaughtException(thread,ex);

//		try
//		{
//			DiaoBaoSharedPreferences.setSharedPreferencesValueToLong("uncaughtException", TimeDateFunction.getCurrTime(), softApp);
//			Intent intent = new Intent(softApp, MainHomeActivity.class);
//			// 如果<span style="background-color: rgb(255, 255, 255); ">没有NEW_TASK标识且</span>是UI线程抛的异常则界面卡死直到ANR
//			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//			softApp.startActivity(intent);
//			android.os.Process.killProcess(android.os.Process.myPid());
//		}catch(Exception ex1)
//		{
//
//		}
//

//		if (threadId != 1) {
//			// 此处示例跳转到汇报异常界面。
//			Intent intent = new Intent(softApp, LoginActivity.class);
//			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//			intent.putExtra("error", info);
//			intent.putExtra("by", "uehandler");
//			softApp.startActivity(intent);
//		} else {
//			// 此处示例发生异常后，重新启动应用
//			Intent intent = new Intent(softApp, LoginActivity.class);
//			// 如果<span style="background-color: rgb(255, 255, 255); ">没有NEW_TASK标识且</span>是UI线程抛的异常则界面卡死直到ANR
//			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//			softApp.startActivity(intent);
//			// write 2 /data/data/<app_package>/files/error.log
//			write2ErrorLog(fileErrorLog, info);
//			// kill App Progress
//			android.os.Process.killProcess(android.os.Process.myPid());
//		}
//		restartApp();
	}

	//重启App
	public void restartApp(){
		Intent intent = new Intent(mContext,MainHomeActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		mContext.startActivity(intent);
		android.os.Process.killProcess(android.os.Process.myPid());  //结束进程之前可以把你程序的注销或者退出代码放在这段代码之前
	}


}